package com.study.ui.other

import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.blankj.utilcode.util.BarUtils
import com.study.ui.R
import com.study.ui.widget.FastBlur
import kotlinx.android.synthetic.main.activity_blur.*


/**
 * <pre>
 *     author : slx
 *     time   : 2021/03/29
 *     desc   :
 * </pre>
 */
class BlurActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_blur)

        // 开启背景模糊
        content.viewTreeObserver.addOnPreDrawListener {
            applyBlur()
            true
        }
    }

    override fun onStart() {
        super.onStart()
        val attributes = window.attributes
        attributes.alpha = 0.8f
        window.attributes = attributes
        Log.i("fauks", "B onStart")
    }

    override fun onRestart() {
        super.onRestart()
        Log.i("fauks", "B onRestart")
    }

    override fun onResume() {
        super.onResume()
        Log.i("fauks", "B onResume")
    }

    override fun onPause() {
        super.onPause()
        Log.i("fauks", "B onPause")
    }

    override fun onStop() {
        super.onStop()
        Log.i("fauks", "B onStop")
    }

    private fun applyBlur() {
        val view = window.decorView
        view.isDrawingCacheEnabled = true
        view.buildDrawingCache(true)
        /**
         * 获取当前窗口快照，相当于截屏
         */
        val bmp1 = view.drawingCache

        /**
         * 除去状态栏和标题栏
         */
        val barHeight = BarUtils.getStatusBarHeight()
        val bmp2 = Bitmap.createBitmap(bmp1, 0, barHeight, bmp1.width, bmp1.height - barHeight);
        blur(bmp2, findViewById(R.id.content))
    }

    private fun blur(bkg: Bitmap, view: View) {
        val scaleFactor = 8f //图片缩放比例；
        val radius = 20f //模糊程度
        var overlay = Bitmap.createBitmap(
                ((view.measuredWidth / scaleFactor).toInt()),
                ((view.measuredHeight / scaleFactor).toInt()),
                Bitmap.Config.ARGB_8888)
        val canvas = Canvas(overlay)
        canvas.translate(-view.left / scaleFactor, -view.top / scaleFactor)
        canvas.scale(1 / scaleFactor, 1 / scaleFactor)
        val paint = Paint()
        paint.flags = Paint.FILTER_BITMAP_FLAG
        canvas.drawBitmap(bkg, 0f, 0f, paint)
        overlay = FastBlur.doBlur(overlay, radius.toInt(), true)
        view.background = BitmapDrawable(resources, overlay)
    }
}